package com.beijing.cyou.service.impl;

import java.util.List;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.beijing.cyou.mapper.UserHelpMappper;
import com.beijing.cyou.model.Group;
import com.beijing.cyou.model.Permission;
import com.beijing.cyou.model.Privilege;
import com.beijing.cyou.model.User;
import com.beijing.cyou.params.HelpParams;
import com.beijing.cyou.params.UserParams;
import com.beijing.cyou.service.UserHelpService;
import com.beijing.cyou.utils.CommonConstant;
import com.beijing.cyou.utils.NotNullHelps;
import com.beijing.cyou.utils.UserHelpConstant;

@Slf4j
@Service
public class UserHelpServiceImpl implements UserHelpService {

	@Autowired
	private UserHelpMappper userHelpMappper;

	private String message;

	@Override
	public Group getGroupInfo(UserParams condition) {
		Group group = null;
		Integer idLevel = condition.getIdLevel();
		Long companyId = condition.getCompanyId();
		if (NotNullHelps.isNotNull(companyId) == false) {
			message = "%% 参数异常！ @@";
		} else {
			group = userHelpMappper.selectGroupById(companyId);
			if (NotNullHelps.isNotNull(group) == false) {
				message = "## KM-组织查询异常！ @@";
			} else {
				Long groupId = group.getGroupId();
				Integer groupSequence = UserHelpConstant.GROUP_SEQUENCE;
				UserParams groupCondition = new UserParams();
				groupCondition.setGroupParentId(groupId);
				groupCondition.setGroupSequence(groupSequence);
				List<Group> subGroups = userHelpMappper.listGroupByParentId(groupCondition);
				if (NotNullHelps.isNotNull(subGroups) == true) {
					UserParams subCondition = new UserParams();
					subCondition.setIdLevel(idLevel);
					for (int i = 0; i < subGroups.size(); i++) {
						Group subGroup = subGroups.get(i);
						Long orgzId = subGroup.getGroupId();
						subCondition.setOrgzId(orgzId);
						List<User> members = userHelpMappper.listUserByOrgzId(subCondition);
						subGroup.setMembers(members);
					}
				}
				group.setSubGroups(subGroups);
				message = "$$ KM-信息查询成功！ @@";
			}
		}
		log.info(message);
		return group;
	}

	@Override
	public Privilege getUserPrivilege(HelpParams condition) {
		Privilege privilege = new Privilege();
		Long userId = condition.getUserId();
		Integer type = condition.getType();
		if (NotNullHelps.checkNotNull(userId, type) == false) {
			message = CommonConstant.common_message_exception;
		} else {
			privilege.setSystemType(UserHelpConstant.SYSTEM_TYPE);

			Permission[] permissionArray = userHelpMappper.arrayUserPermission(condition);

			if (NotNullHelps.isNotNull(permissionArray) == false) {
				message = "$$ 权限暂无，正在补充中 @@";
			} else {
				message = "&& 用户base权限 查询成功！ @@";
			}

			privilege.setPermissions(permissionArray);

		}
		log.info(message);
		return privilege;
	}

}
